<template>
	<u-popup :mask-close-able="false" :custom-style="customStyle" border-radius="14" v-model="computedShow"
		mode="bottom" height="90%">
		<view class="title">
			<text>{{taskConfig.title}}</text>
		</view>

		<view class="scroll-Y">
			<u-tabs-swiper ref="uTabs" :list="list" name="taskType" :current="current"
				@change="tabsChange"></u-tabs-swiper>
			<swiper class="swiper" :current="swiperCurrent" @animationfinish="animationfinish">
				<swiper-item class="swiper_item" v-for="(item,index) in list">
					<u-card :show-head="false">
						<view slot="body">
							<view class="action"
								v-if="(taskConfig.type=='edit'&&actionStatus())||taskConfig.type=='create'">
								<u-button
									v-if="(list.length!=1&&item.taskType!='年度任务'&&item.taskType!='月度任务')||taskConfig.type=='create'"
									type="error" size="mini" :plain="true" @click="deleteTool(index)">删除</u-button>
							</view>
							<u-cell-item :disabled="taskConfig.type=='view'" title="任务类型:"
								:value="item.taskType == '' ? '请选择' : item.taskType"
								@click="  listIndex = index; taskConfig.type=='create'||(false&&taskConfig.type!='view'&&infoEditStatus()&&item.taskType!='其他任务')?show_picker = true :'';selece_type='taskType'; columns = taskTypeOptions;label_name = 'value';value_name = 'code'; ">
							</u-cell-item>

							<u-cell-item v-if="item.taskType!='其他任务'" :disabled="taskConfig.type=='view'" title="任务名称:"
								:value="!item.taskYearName  ? '请选择' : item.taskYearName"
								@click=" listIndex = index; taskConfig.type=='create'||(item.taskType!='年度任务'&&item.taskType!='月度任务'&&taskConfig.type!='view'&&infoEditStatus())? getTaskList() :'';selece_type='taskYearName'; columns = taskOptions;label_name = 'label';value_name = 'value'; ">
							</u-cell-item>
							<u-field v-else @input='taskNameInput' @click="listIndex=index"
								:disabled="taskConfig.type=='view'" v-model="item.taskName" label="任务名称:"
								placeholder="请填写"></u-field>
							<u-cell-item :disabled="taskConfig.type=='view'" title="地点:"
								:value="!item.taskLocationName? '请选择' : item.taskLocationName"
								@click="  listIndex = index;  taskConfig.type=='create'||(item.taskType!='年度任务'&&item.taskType!='月度任务'&&taskConfig.type!='view'&&infoEditStatus())? getTaskDetailAndStation()  :'';selece_type='taskLocationName'; columns = optionStation;label_name = 'stationName';value_name = 'stationId'; ">
							</u-cell-item>
							<u-cell-item v-if="returnStatus(item)" :disabled="taskConfig.type=='view'" title="设备类型:"
								:value="!item.equTypeName ? '请选择' : item.equTypeName"
								@click=" listIndex = index;  taskConfig.type=='create'||(item.taskType!='年度任务'&&item.taskType!='月度任务'&&taskConfig.type!='view'&&infoEditStatus())? getTaskDetailAndStation()  :'';selece_type='equTypeName'; columns = optionEqu;label_name = 'equtypename';value_name = 'idK'; ">
							</u-cell-item>
							<u-cell-item :disabled="taskConfig.type=='view'" v-if="returnStatus(item)" title="设备:"
								:value="item.equName?item.equName:'请选择'"
								@click=" listIndex = index; selece_type='equName'; taskConfig.type=='create'||(item.taskType!='年度任务'&&item.taskType!='月度任务'&&taskConfig.type!='view')? show_device = true :'';  getEquList();deviceName=item.equName">
							</u-cell-item>
							<!-- <u-cell-item class="deviceTable" v-if="item.equName" :arrow="item.equName?false:true">
								<u-table padding="0 0">
									<u-tr>
										<u-th width="60%">设备名称</u-th>
										<u-th width="40%">设备状态</u-th>
									</u-tr>
									<view class='tableClass'>
										<u-tr v-for="(items,indexs) in item.equName.split(',')">
											<u-td width="60%">{{items}}</u-td>
											<u-td width="40%">
												<view>
													<u-icon :name="returnIcon(indexs).name" :color="returnIcon(indexs).color"
														size="28"></u-icon>
												</view>
											</u-td>
					
										</u-tr>
									</view>
					
								</u-table>
							</u-cell-item> -->
							<view class="rowClass">
							</view>


							<!-- <u-cell-item title="开始时间:" :value="item.startTime == '' ? '请选择' : item.startTime" @click="
										taskConfig.type!='view'&&infoEditStatus()?show_date = true:''; listIndex = index;
										date_type = 'startTime';">
							</u-cell-item>
							<u-cell-item title="结束时间:" :value="item.endTime == '' ? '请选择' : item.endTime" @click="
									taskConfig.type!='view'&&infoEditStatus()?show_date = true:'';
									listIndex = index;
									date_type = 'endTime';">
							</u-cell-item> -->

							<u-field class="ufield" :disabled="taskConfig.type=='view'&&infoEditStatus()"
								input-align="right" v-model="item.detailedContent" label="    具体内容:" placeholder="请填写"
								type="textarea"></u-field>

						</view>
					</u-card>
				</swiper-item>
			</swiper>

		</view>
		<view class="footer">
			<u-button :plain="true" type="primary" size="medium" :ripple="true"
				@click="computedShow=false">关闭</u-button>
			<u-button v-if="taskConfig.type=='edit'||taskConfig.type=='create'" size="medium" :ripple="true"
				type="primary" @click="confirm">保存</u-button>
			<u-button type="primary " size="medium" :plain="true" @click="add()">新增任务</u-button>
			<!-- 	<u-button
				v-if="taskConfig.type=='edit'&&deviceShow()&&butSelect==1"
				size="medium" :ripple="true" type="primary" @click="deviceList">设备检修</u-button> -->
			<!-- 	<u-button
					v-if="(taskConfig.type=='edit'&&deviceShow()||taskParam.typeid!=2&&taskConfig.type=='view'||taskParam.typeid==2&&taskConfig.type=='view'&&deviceShow())&&butSelect==1"
					size="medium" :ripple="true" type="primary" @click="deviceList">设备详情</u-button> -->
		</view>
		<u-select v-model="show_picker" :list="columns" :label-name="label_name" :value-name="value_name"
			@confirm="onConfirm" @cancel="onCancel">
		</u-select>
		<u-picker v-model="show_date" mode="time" :params="params" @confirm="setDate" @cancel="onCancel"></u-picker>
		<selectDevice v-show="show_device" :deviceName="deviceName" :device="optionEquName" @close="show_device = false"
			@setDevice="setDevice"></selectDevice>
	</u-popup>
</template>

<script>
	import selectDevice from './selectDevice.vue'
	import {

		DICCONTROLLER
	} from "../../../api/sys";
	import {
		EQUCONTROLLER
	} from '../../../api/eqt.js'
	import {

		WORK_CONTROLLER,

	} from "../../../api/pms";

	export default {
		components: {
			selectDevice
		},
		props: {
			show: {
				type: Boolean,
				default: false
			},
			taskConfig: {
				type: Object
			},
			taskParam: {
				type: Object
			}
		},
		computed: {
			computedShow: {
				get() {
					return this.show
				},
				set(val) {
					this.$emit("update:show", val)
				},
			},
		},
		watch: {
			"taskConfig.data": {
				handler(val) {
					if (val.length) {
						this.list = []
						val.forEach(item => {
							if (item.equDetailList) {
								item.equName = item.equDetailList.map(mapitem => mapitem.equName).toString()
								item.equId = item.equDetailList.map(mapitem => mapitem.equId).toString()
							}
						})
						this.list = val
					} else {

					}
				},
				deep: true,
				immediate: true
			},
			"selece_type": {
				async handler(newVal) {

				},

			}
		},
		async created() {
			const res7 = await this.fetch(
				"post",
				this.$store.state.baseUrl + DICCONTROLLER.DICLISTSBYDICTYPE, {
					dicClass: "task_type" // 任务类型
				},
				false
			);
			this.taskTypeOptions = res7?.data
			console.log(this.taskParam)
			this.config.woSn = this.taskParam.woSn
			this.getSelecConfig()
		},
		data() {
			return {
				taskOptions: [], // 任务列表
				taskTypeOptions: [], // 任务类型列表
				optionEqu: [], // 设备类型
				optionStation: [], // 车站
				optionEquName: [], // 设备
				showDevice: true, // 是否显示 设备类型和设备
				deviceName: "", // 设备名称
				show_device: false,
				columns: [],
				// computedColumns:[],
				listIndex: 0,
				show_date: false,
				selece_type: "",
				label_name: "",
				value_name: "",
				show_picker: false,
				params: {
					year: true,
					month: true,
					day: true,
					hour: true,
					minute: true,
					second: true,
				},
				customStyle: {
					display: "flex",
					flexDirection: "column"
				},
				scrollTop: 0,
				list: [{
					taskType: '',
					taskYearName: "",
					taskName: "",
					equID: "",
					equName: "",
					equTypeID: "",
					equTypeName: "",
					orderNumber: "",
					taskLocation: "",
					taskLocationName: "",
					endTime: "",
					startTime: '',
					detailedContent: "",

				}],
				equStatus: [{
						status: '0',
						name: "checkbox-mark",
						tpye: '',
						color: '#2979ff'
					}, {
						status: '1',
						name: "close",
						tpye: '',
						color: '#fa3534'
					},
					{
						status: '2',
						name: "eye",
						tpye: '',
						color: '#909399'
					},
				],
				config: {
					pmsEquControl: '',
					pmsNfcShow: "",
					pmsScanCode: "",
					woSn: ''
				},
				butSelect: "",
				woSn: '',
				swiper: [{

				}],
				current: 0,
				swiperCurrent: 0
			}
		},
		methods: {
			getEquTypeByStationId(param) {
				let editItem = this.list[this.listIndex]
				if (!editItem.taskLocation) {
					uni.showToast({
						title: "请先选择问题地点~",
						icon: "none",
					});
					return
				}
				this.columns = []
				this.fetch(
					"GET",
					this.$store.state.baseUrl + EQUCONTROLLER.GET_EQU_TYPE_BY_STATIONID, {
						stationId: editItem.taskLocation,
					}, false
				).then((res) => {
					if (res.returnCode == 2004) {
						this.label_name = 'name'
						this.value_name = 'idk'
						this.columns = res?.data
						this.show_picker = true
					} else {
						this.label_name = 'name'
						this.value_name = 'idk'
						this.columns = []
						this.show_picker = true
					}
				})
			},
			animationfinish(e) {
				let current = e.detail.current
				this.$refs.uTabs.setFinishCurrent(current)
				this.swiperCurrent = current
				this.current = current
			},
			tabsChange(index) {
				this.swiperCurrent = index
			},
			// 接口获取显示按钮
			getSelecConfig() {
				this.fetch(
					"POST",
					this.$store.state.baseUrl + WORK_CONTROLLER.Post_Operation_SelectConfig, {}, false
				).then((res) => {
					if (res?.returnCode == '2004') {

						this.config.pmsEquControl = res.data.pmsEquControl
						this.config.pmsNfcShow = res.data.pmsNfcShow
						this.config.pmsScanCode = res.data.pmsScanCode
						this.butSelect = res.data.pmsEquControl

					}
				})
			},
			returnIcon(param) {
				let filterArr = this.equStatus.filter(item => item.status == param)

				return filterArr.length ? filterArr[0] : {
					status: '',
					name: "",
					tpye: '',
					color: ''
				}
			},
			deviceShow() {
				let showState = false
				let woState = this.taskParam.woState
				let arr = ['进行中', '待提交']
				arr.includes(woState) ? showState = true : showState = false
				return showState
			},
			infoEditStatus() {
				// 接单 任务列表只可以修改 设备
				let showState = false
				let woState = this.taskParam.woState
				let arr = [null, '准备中', '待接单']
				arr.includes(woState) ? showState = false : showState = true
				return showState
			},
			actionStatus() {
				// 派发和接单任务不可以新增或者删除
				let showState = false
				let woState = this.taskParam.woState
				let arr = ['待派单', '已创建', '待接单', '待下发']
				arr.includes(woState) ? showState = false : showState = true
				return showState
			},
			deviceList() {
				this.$store.commit('setTaskList', this.list)
				uni.navigateTo({
					url: '/pages/productCenter/deviceList?btn=' + this.butSelect + "&type=" + this.taskConfig
						.type + '&config=' + JSON.stringify(this.config)
				})
			},
			returnStatus(item) {
				let status
				if (!item?.taskYearName) {
					status = true
				} else {
					item?.taskYearName?.indexOf('按任务') == -1 ? status = true : status = false
				}
				return status
			},
			setDevice(obj) {
				this.list[this.listIndex].equName = obj.name.toString();
				this.list[this.listIndex].equID = obj.id.toString();
				this.show_device = false;
			},
			// 任务名称手输 
			taskNameInput(a) {
				let editItem = this.list[this.listIndex]
				console.log(a, this.listIndex, this.list, 111);
				editItem.taskYearName = a
				editItem.taskName = a
				console.log(editItem, 222);
				this.list[this.listIndex] = editItem
			},
			/**
			 *  根据某一个任务id 获取 该任务的详情，设备类型，和地点。
			 */
			async getTaskDetailAndStation(param) {
				this.columns = []
				let editItem = this.list[this.listIndex]

				await this.fetch(
					"GET",
					this.$store.state.baseUrl + WORK_CONTROLLER.GET_WORK_TASKORG, {
						idK: editItem.yearMonthId
					}, false
				).then((res) => {
					if (res?.success) {
						this.optionEqu = res?.data?.taskEqutype;
						this.optionStation = res?.data?.taskStation.filter((i) => {
							return this.taskParam.stations?.includes(i.stationId);
						});
						if (this.selece_type == 'equTypeName' && editItem.taskType != '其他任务') {
							this.show_picker = true
							this.columns = res?.data?.taskEqutype.filter(item => item)
						}
						if (this.selece_type == 'equTypeName' && editItem.taskType == '其他任务') {
							this.getEquTypeByStationId()
						}
						if (this.selece_type === 'taskLocationName') {
							this.show_picker = true
							this.columns = this.optionStation
						}
					}
				})


			},
			/**
			 * 根据选择的设备类型获取 设备列表 
			 */
			async getEquList() {
				if (this.selece_type = 'equName') {
					await this.getTaskDetailAndStation()
				}
				let editItem = this.list[this.listIndex]
				let code = this.optionStation.filter(
					(i) => i.stationId == editItem.taskLocation
				)[0]?.stationCode;
				this.fetch(
					"post",
					this.$store.state.baseUrl + WORK_CONTROLLER.POST_EQU_EQULIST, {
						equtype: editItem.equTypeID,
						station: code,
						page: 1,
						size: 9999999,
					}, false
				).then((res) => {
					if (res?.data) {
						this.optionEquName = res?.data?.content;
						// [{
						// 	equname: "设备1",
						// 	idk: "001"
						// }, {
						// 	equname: "设备2",
						// 	idk: "002"
						// }, {
						// 	equname: "设备3",
						// 	idk: "003"
						// }, {
						// 	equname: "设备4",
						// 	idk: "004"
						// }, {
						// 	equname: "设备5",
						// 	idk: "005"
						// }, {
						// 	equname: "设备6",
						// 	idk: "006"
						// },
						// {
						// 	equname: "2",
						// 	idk: "f3a1bd7897ea48c389a7d19455c69baf"
						// },
						// {
						// 	equname: "5/7",
						// 	idk: "189dff5ac91042fc93de6594aec1cb10"
						// }
						// ]
						//res?.data?.content;
						this.optionEquName = this.reduceArray(this.optionEquName, "idk");
					}
				})
			},
			// 数组对象元素去重
			reduceArray(initialArr, attr) {
				// const uniqueArr = Array.from(new Set(arr.map(JSON.stringify)), JSON.parse);
				let uniqueArr = initialArr.reduce((acc, obj) => {
					let existingObj = acc.find((item) => item[attr] === obj[attr]);
					if (!existingObj) {
						acc.push(obj);
					}
					return acc;
				}, []);
				return uniqueArr;
			},
			/**
			 *  根据选择是任务类型，获取对应的任务列表
			 */
			getTaskList() {
				let task = this.list[this.listIndex]
				let param = {
					type: task.taskType == "年度任务" ? 1 : 2,
					year: new Date(this.taskParam.startTime).getFullYear(),
					month: task.taskType == "年度任务" ?
						"" : new Date(this.taskParam.startTime).getMonth() + 1,
					// stationId: this.taskParam?.stations?.toString(),
					pageSize: 100000,
					pageNo: 1,
				}
				this.fetch(
					"GET",
					this.$store.state.baseUrl + WORK_CONTROLLER.GET_YEARREPORT, param, false
				).then((res) => {
					if (res?.success) {
						this.taskOptions = res?.data?.content.map((i) => {
							return {
								label: i.project,
								value: i.taskId,
								job: i.workContent,
								yearMonthId: i.id,
							};
						});
						if (this.selece_type == 'taskYearName') {
							this.show_picker = true
							this.columns = this.taskOptions
						}
					}
				});
			},
			onConfirm(item) {
				let editItem = this.list[this.listIndex]
				switch (this.selece_type) {
					case "taskType":
						editItem.taskType = item[0].label
						editItem.taskName = item[0].value
						this.getTaskList()
						editItem.taskYearName = ''
						editItem.taskName = ''
						editItem.detailedContent = ''
						editItem.yearMonthId = ''
						break;
					case "taskYearName":
						editItem.taskYearName = item[0].label
						editItem.taskName = item[0].value
						editItem.yearMonthId = item[0].yearMonthId
						let filterContent = this.taskOptions.filter(items => {
							return items.value == item[0].value
						})
						editItem.detailedContent = filterContent[0].job
						editItem.yearMonthId = filterContent[0].yearMonthId
						editItem.major =
							filterContent[0]?.major || "";
						if (editItem.taskYearName.indexOf("按任务") !== -1) {
							editItem.equID = "";
							editItem.equName = "";
							editItem.equTypeName = "";
							editItem.equTypeID = "";
							this.showDevice = false
						}
						editItem.taskLocationName = ""
						editItem.taskLocation = ""
						editItem.equTypeName = ''
						editItem.equTypeID = ''
						this.getTaskDetailAndStation()
						break;
					case "taskLocationName":
						editItem.taskLocationName = item[0].label
						editItem.taskLocation = item[0].value
						break;
					case "equTypeName":
						editItem.equTypeName = item[0].label
						editItem.equTypeID = item[0].value
						this.getEquList()
						break;
					case "equName":
						break;
					default:
						this.list[this.listIndex] = editItem
				}

				this.onCancel();
			},
			setDate(obj) {
				let str =
					obj.year +
					"-" +
					obj.month +
					"-" +
					obj.day +
					" " +
					obj.hour +
					":" +
					obj.minute +
					":" +
					obj.second;
				switch (this.date_type) {
					case "startTime":
						this.list[this.listIndex].startTime = str
						break;
					case "endTime":
						this.list[this.listIndex].endTime = str
					default:
				}
				this.onCancel();
			},
			onCancel() {
				this.show_picker = false;
				this.show_date = false;

			},
			confirm() {
				let status = true
				this.list.forEach((item, inde) => {
					let restatus = this.taskConfig.type !== "create" ? this.checkData(item) : true
					if (!restatus) {
						status = restatus
					}
				})
				if (!status) return
				uni.showToast({
					title: "作业任务保存成功",
					icon: "none",
				});
				this.$emit('passTaskData', this.list)
			},
			add(param) {
				// let item = this.list[param]
				// let status = this.checkData(item)
				// if (!status) return
				console.log('this.taskConfig', this.taskConfig)
				if (this.taskConfig.type == "edit") {
					this.list.push({
						taskType: '其他任务',
						taskYearName: "",
						taskName: "",
						equID: "",
						equName: "",
						equTypeID: "",
						equTypeName: "",
						orderNumber: "",
						taskLocation: "",
						taskLocationName: "",
						endTime: "",
						startTime: '',
						detailedContent: "",
					})
				} else if (this.taskConfig.type == 'create') {
					this.list.push({
						taskType: "其他任务",
						taskYearName: "",
						taskName: "",
						equID: "",
						equName: "",
						equTypeID: "",
						equTypeName: "",
						orderNumber: "",
						taskLocation: "",
						taskLocationName: "",
						endTime: "",
						startTime: '',
						detailedContent: "",
					})
				}
			},
			checkData(obj) {

				if (!obj?.taskType) {
					uni.showToast({
						title: "请选择任务类型",
						icon: "none",
					});
					return false
				}
				if (!obj?.taskName) {
					uni.showToast({
						title: "请填写任务名称",
						icon: "none",
					});
					return false
				}
				if (!obj?.taskLocationName) {
					uni.showToast({
						title: "请选择地点",
						icon: "none",
					});
					return false
				}
				if (!obj?.equTypeName && this.returnStatus(obj)) {
					uni.showToast({
						title: "请选择设备类型",
						icon: "none",
					});
					return false
				}
				return true
				// if (!obj?.equName && this.returnStatus(obj)) {
				// 	uni.showToast({
				// 		title: "请选择设备",
				// 		icon: "none",
				// 	});
				// 	return false
				// }
			},
			deleteTool(index) {
				this.list.splice(index, 1)
				this.current = index - 1
				this.swiperCurrent = index - 1
			}
		},

	}
</script>

<style scoped lang="less">
	// .swiper_item {
	// 	display: flex;
	// 	flex-direction: column;
	// }

	/deep/.swiper {
		height: 100%;
	}

	// /deep/.u-tabs-scroll-box {
	// 	display: flex;
	// 	flex-direction: row;
	// }

	// /deep/.u-tabs-item {
	// 	// flex: 1;
	// }

	.u-field {
		padding-left: 8px !important;
	}

	.tableClass {
		max-height: 140px;
		overflow-y: auto;
	}

	/deep/.deviceClass {}

	.scroll-Y .deviceTable {
		padding-top: 0px !important;
	}

	.rowClass {
		display: flex;
		flex-direction: row;

		&:nth-child(2) {
			// padding-left: 5px!important;
		}

	}

	.footer {
		display: flex;
		flex-direction: row;
		justify-content: flex-end;

		.u-btn {
			width: 100rpx;
			margin-left: 20px;
		}

		padding: 10px 20px;
	}

	.scroll-Y {
		height: calc(90vh - 100px);
	}

	.title {
		padding: 10px;
		font-weight: 600;
		text-align: center;
	}

	.action {
		text-align: right;

		.u-btn {
			width: 70px;
			margin-left: 10px;
		}

		// :nth-child(2) {
		// 	margin-left: 10px;
		// 	margin-right: 10px;
		// }
	}
</style>